// user.js
const app = getApp()
const api = require('../../utils/api')

Page({
  data: {
    userInfo: {},
    isLoggedIn: false,
    isLoading: true
  },

  onLoad() {
    this.loadUserInfo()
  },

  onShow() {
    // 每次显示页面时重新加载用户信息
    this.loadUserInfo()
  },

  async loadUserInfo() {
    try {
      const userInfo = wx.getStorageSync('userInfo')
      const token = wx.getStorageSync('token')
      
      // 确保商家登录信息不会影响到用户页面
      const merchantInfo = wx.getStorageSync('merchantInfo')
      if (merchantInfo && !userInfo) {
        this.setData({
          userInfo: {},
          isLoggedIn: false,
          isLoading: false
        })
        return
      }
      
      // 如果有token但没有用户信息，尝试从服务器获取
      if (token && !userInfo) {
        const res = await api.getUserInfo()
        if (res.success) {
          wx.setStorageSync('userInfo', res.data)
          this.setData({
            userInfo: res.data,
            isLoggedIn: true,
            isLoading: false
          })
          return
        }
      }
      
      this.setData({
        userInfo: userInfo || {},
        isLoggedIn: !!(userInfo && token),
        isLoading: false
      })
    } catch (error) {
      console.error('Failed to load user info:', error)
      this.setData({
        isLoading: false
      })
    }
  },

  goToLogin() {
    if (this.data.isLoading) return
    wx.navigateTo({
      url: '/pages/login/login',
      events: {
        // 监听登录成功事件
        loginSuccess: (userInfo) => {
          this.setData({
            userInfo: userInfo,
            isLoggedIn: true
          })
        }
      },
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  handleLogout() {
    if (this.data.isLoading) return
    wx.showModal({
      title: '提示',
      content: '确定要退出登录吗？',
      success: (res) => {
        if (res.confirm) {
          // 使用API登出方法
          api.logout().then(() => {
            this.setData({
              userInfo: {},
              isLoggedIn: false
            })
            wx.showToast({
              title: '已退出登录',
              icon: 'success'
            })
          }).catch(err => {
            console.error('登出出错:', err)
            // 即使API调用失败，也清除本地状态确保用户体验
            this.setData({
              userInfo: {},
              isLoggedIn: false
            })
          })
        }
      }
    })
  },

  goToOrders(e) {
    if (this.data.isLoading) return
    const type = e.currentTarget.dataset.type
    wx.navigateTo({
      url: `/pages/order/order?type=${type}`,
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  goToAddress() {
    if (this.data.isLoading) return
    wx.navigateTo({
      url: '/pages/address/address',
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  goToReviews() {
    if (this.data.isLoading) return
    wx.navigateTo({
      url: '/pages/reviews/reviews',
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  },

  goToPurchaseHistory() {
    if (this.data.isLoading) return
    
    console.log('跳转到购买历史页面');
    
    // 跳转到订单页面，默认显示已完成的订单并显示评价按钮
    wx.navigateTo({
      url: '/pages/order/order?type=completed&showReviewButtons=true',
      success: (res) => {
        console.log('跳转到购买历史页面成功');
      },
      fail: (err) => {
        console.error('跳转到购买历史页面失败:', err);
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        });
      }
    });
  },

  goToMerchant() {
    if (this.data.isLoading) return
    wx.navigateTo({
      url: '/pages/admin/login/login',
      fail: (err) => {
        console.error('Navigation failed:', err)
        wx.showToast({
          title: '页面跳转失败',
          icon: 'none'
        })
      }
    })
  }
}) 